import { Application } from "maishu-chitu-react";
import { ComponentContainer } from "../components/component-container";
import { Component } from "maishu-jueying";
import { ValueStore, PageData } from "maishu-chitu";
import { MasterPage } from "components/common/master-page";
import { BaseComponent } from "components/common/base-component";
import { MemberService } from "./services/memberService";
import * as ui from "maishu-ui-toolkit";
import { errorHandle } from "./error-handle";
import { USER_APP, urlParams } from "common";
import { isWeixin } from "./services/weixinService";
import { Service } from "services/service";
import { LocalService } from "./services/localService";
// import { contextName } from "../constants";
import websiteConfig = require("json!websiteConfig");


let modulesPath = "mobile/modules";
export class UserApplication extends Application {

    private wx: any;
    private _forward: Application["forward"];

    constructor(container?: HTMLElement) {
        super({ container });

        this.pageTagName = "article";
        this._forward = super.forward;



        let localService = this.createService(LocalService);
        this.pageCreated.add(async (sender, page) => {
            let name = page.name == "page" ? "" : page.name.split("/").join("-");
            page.element.className = "mobile-page " + name;

            let files = await localService.clientFiles();
            let lessFilePath = `${modulesPath}/${page.name}.less`;
            let pageLessFiles = files.filter(o => o.startsWith(modulesPath) && o.endsWith(".less"));
            if (pageLessFiles.indexOf(lessFilePath) >= 0)
                this.loadLess(lessFilePath);

        });

        let memberService = this.createService(MemberService);
        memberService.store().then(o => {
            let styleColor: StyleColor = "default";
            if (o != null && o.Style != null)
                styleColor = o.Style;

            BaseComponent.loadLessFile("baseStyle", styleColor, "components/style/baseStyle");
        })

        this.error.add((sender, error) => errorHandle(error, sender));
        this.createDialogContainer();

    }

    loadjs(path: string) {
        return new Promise<any>((reslove, reject) => {
            requirejs({ context: websiteConfig.requirejs.context }, [path], function (result) {
                reslove(result);
            }, function (err) {
                reject(err);
            });
        });
    }

    async getWX(): Promise<any> {
        if (this.wx)
            return this.wx;

        return new Promise((resolve, reject) => {
            requirejs(["https://res.wx.qq.com/open/js/jweixin-1.3.2.js"],
                (wx) => {
                    this.wx = wx;
                    resolve(wx)
                },
                err => {
                    reject(err)
                }
            )
        })
    }

    forward(pageUrl: string, args?: PageData) {
        let url = encodeURIComponent(pageUrl);
        if (!isWeixin) {
            return this._forward.apply(this, [pageUrl, args]);
        }

        this.getWX().then(wx => {
            wx.miniProgram.getEnv((res) => {
                if (res.miniprogram) {
                    let routeData = this.parseUrl(url);
                    args = Object.assign({}, args || {}, routeData.values);
                    let obj = encodeURIComponent(JSON.stringify(args));
                    wx.miniProgram.navigateTo({ url: `../webview-page/webview-page?url=${routeData.pageName}&args=${obj}` });
                    return;
                }

                this._forward.apply(this, [pageUrl, args]);
            })
        })

        return null;
    }

    // 处理通过 URL 传过来的数据, 一般用于小程序
    // 从小程序主程序传给浏览器
    async processURLParams() {
        let token = urlParams["token"];
        if (token != null) {
            Service.token.value = token;
        }
    }

    async run() {
        await this.processURLParams();
        super.run();
    }

    createDialogContainer() {
        let dialogContainer = document.createElement("div");
        dialogContainer.className = "mobile-page";
        document.body.appendChild(dialogContainer);
        ui.dialogConfig.dialogContainer = dialogContainer;
    }

    private loadLess(filePath: string) {
        requirejs({ context: websiteConfig.contextName }, [`less!${filePath}`], () => {
        })
    }
}

export let app = window[USER_APP] = window[USER_APP] || new UserApplication();




